package com.py.inbound.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.py.api.PyCodeApi;
import com.py.inbound.domain.*;
import com.py.inbound.service.IPyInboundDetalisService;
import com.ruoyi.common.core.utils.PageUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.py.inbound.domain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.py.inbound.domain.PyInbound;
import com.py.inbound.service.IPyInboundService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

import static com.ruoyi.common.core.utils.PageUtils.startPage;

/**
 * 入库管理Controller
 *
 * @author py
 * @date 2024-11-21
 */
@RestController
@RequestMapping("/inbound")
public class PyInboundController extends BaseController {
    @Autowired
    private IPyInboundService pyInboundService;
    @Autowired
    private IPyInboundDetalisService pyInboundDetalisService;
    @Resource
    private PyCodeApi pyCodeApi;


    /**
     * 入库排名
     */
    @GetMapping("/ranking")
    public List<PyInbound> selectPyInboundRanking() {
        System.out.println(pyInboundService.selectPyInboundRanking());
        return pyInboundService.selectPyInboundRanking();
    }


    /**
     * 入库统计
     */
    @RequestMapping("/date")
    public StatisticsDate selectPyInboundStatistics(DateBeginEnd dateBeginEnd) {
        System.out.println("dateBeginEnd:" + dateBeginEnd);
        return pyInboundService.selectPyInboundStatistics(dateBeginEnd);
    }

    /**
     * 获取编码
     */
    @PostMapping("/getcode")
    public Map<String, Object> getCode(@RequestParam(value = "code", required = false) Integer code) {
        return pyCodeApi.generateCode(code);
    }

    /**
     * 查询入库管理列表
     */
    @RequiresPermissions("inbound:inbound:list")
    @GetMapping("/list")
    public TableDataInfo list(PyInbound pyInbound) {
        startPage();
        List<PyInbound> list = pyInboundService.selectPyInboundList(pyInbound);
        return getDataTable(list);
    }

    /**
     * 导出入库管理列表
     */
    @RequiresPermissions("inbound:inbound:export")
    @Log(title = "入库管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PyInbound pyInbound) {
        List<PyInbound> list = pyInboundService.selectPyInboundList(pyInbound);
        ExcelUtil<PyInbound> util = new ExcelUtil<PyInbound>(PyInbound.class);
        util.exportExcel(response, list, "入库管理数据");
    }

    /**
     * 获取入库管理详细信息
     */
    @RequiresPermissions("inbound:inbound:query")
    @GetMapping(value = "/{inventoryId}")
    public AjaxResult getInfo(@PathVariable("inventoryId") Long inventoryId) {
        PyInbound pyInbound = pyInboundService.selectPyInboundByInventoryId(inventoryId);
//        System.out.println("getInventoryNumber:" + pyInbound.getInventoryNumber());
        List<PyInboundDetalis> pyInboundDetalis = null;
        if (pyInbound.getInventoryType() == 0) {
            pyInboundDetalis = pyInboundDetalisService.SelectAllupdatePyInboundDetalis(pyInbound.getInventoryNumber());
        } else if (pyInbound.getInventoryType() == 1) {
            pyInboundDetalis = pyInboundDetalisService.SelectAllupdatePyInboundDetalisTH(pyInbound.getInventoryNumber());

        }
//        System.out.println("pyInboundDetalis详情:" + pyInboundDetalis);
        HashMap map = new HashMap();
        map.put("pyInbound", pyInbound);
        map.put("pyInboundDetalis", pyInboundDetalis);

        return success(map);
    }

    /**
     * 修改入库管理
     */
    @RequiresPermissions("inbound:inbound:edit")
    @Log(title = "入库管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PyInbound pyInbound) {

        return toAjax(pyInboundService.updatePyInbound(pyInbound));
    }

    /**
     * 删除入库管理
     */
    @RequiresPermissions("inbound:inbound:remove")
    @Log(title = "入库管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{inventoryIds}")
    public AjaxResult remove(@PathVariable Integer[] inventoryIds) {
        return toAjax(pyInboundService.deletePyInboundByInventoryIds(inventoryIds));
    }

    /**
     * 查询进货部门
     */
    @GetMapping("/selectAllSysDept")
    public List<SysDept> selectAllSysDept() {
//        List<SysDept> list=pyInboundService.selectAllSysDept();
//        list.forEach(System.out::println);
        return pyInboundService.selectAllSysDept();
    }

    /**
     * 查询进货部门
     */
    @GetMapping("/selectAllSysDeptByID")
    public List<SysDept> selectAllSysDeptByID(@RequestParam("deptid") Long deptid) {
        return pyInboundService.selectAllSysDeptByParentId(deptid);
    }

    @GetMapping("/selectAllSysUserByParentId")
    public List<SysUser> selectAllSysUserByParentId(@RequestParam("deptid") Long deptid) {
        return pyInboundService.selectAllSysUserByParentId(deptid);
    }

    @GetMapping("/selectAllPySuppliers")
    public AjaxResult selectAllPySuppliers() {
        return success(pyInboundService.selectAllPySuppliers());

    }

    @GetMapping("/selectAllBsWarehouse")
    public AjaxResult selectAllBsWarehouse() {
        return success(pyInboundService.selectAllBsWarehouse());

    }

    @GetMapping("/selectSuppliersByid")
    public AjaxResult selectSuppliersByid(@RequestParam("supplierId") Long supplierId) {

        PySuppliers pySuppliers = pyInboundService.selectSuppliersByid(supplierId);


        return new AjaxResult(200, "成功", pySuppliers);

    }

    @GetMapping("/selectAllOdPurchaseOrder")
    public TableDataInfo selectAllOdPurchaseOrder(OdPurchaseOrder odPurchaseOrder) {
        startPage();
        List<OdPurchaseOrder> odPurchaseOrders = pyInboundService.selectAllOdPurchaseOrder(odPurchaseOrder);
//        System.out.println("撒大大:" + odPurchaseOrders);
        return getDataTable(odPurchaseOrders);

    }

    @GetMapping("/selectAllOdInRejected")
    public AjaxResult selectAllOdInRejected(OdInRejected odInRejected) {

        List<OdInRejected> odInRejecteds = pyInboundService.selectAllOdInRejected(odInRejected);
        return success(odInRejecteds);

    }

    @GetMapping("/selectAllOdPurchaseDetails")
    public TableDataInfo selectAllOdPurchaseDetails(@RequestParam(value = "phCodes", required = false) String phCodes,
                                                    @RequestParam(value = "productCode", required = false) String productCode) {
//        System.out.println("phCodes:" + phCodes);
//        System.out.println("productCode:" + productCode);
        startPage();
        OdPurchaseDetails odPurchaseDetails = new OdPurchaseDetails();
        odPurchaseDetails.setPhCode(phCodes);
        odPurchaseDetails.setProductCode(productCode);
        List<OdPurchaseDetails> odPurchaseDetails1 = pyInboundService.selectAllOdPurchaseDetails(odPurchaseDetails);
//        odPurchaseDetails1.forEach(s -> System.out.println("打印:" + odPurchaseDetails1));
        return getDataTable(odPurchaseDetails1);

    }


    @GetMapping("/selectWhInventoryByCode")
    public AjaxResult selectWhInventoryByCode(@RequestParam("location") String location,
                                              @RequestParam("productCode") String productCode) {

        WhInventory whInventory = new WhInventory();
        whInventory.setLocationCode(location);
        whInventory.setProductCode(productCode);
        List<WhInventory> whInventories = pyInboundService.selectWhInventoryByCode(whInventory);

//        System.out.println("集合:" + whInventories);
        return success(whInventories);

    }

    @GetMapping("/selectAllBsWhLocation")
    public AjaxResult selectAllBsWhLocation(@RequestParam("warehouseId") Integer warehouseId) {

        System.out.println("仓库id:" + warehouseId);
        return success(pyInboundService.selectAllBsWhLocation(warehouseId));

    }

    /**
     * 新增入库管理
     */
    @RequiresPermissions("inbound:inbound:add")
    @Log(title = "入库管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody PyInbound pyInbound) {
        System.out.println("添加入库:" + pyInbound);
        System.out.println("添加入库明细:" + pyInbound.getPyInboundDetalisList());
        pyCodeApi.saveCode(pyInbound.getCodeId(), pyInbound.getNumber());
        // 检查入库明细列表是否为空
        if (pyInbound.getPyInboundDetalisList() == null || pyInbound.getPyInboundDetalisList().isEmpty()) {
            return AjaxResult.warn("入库明细列表为空，不允许入库操作！", null);
        }

        for (PyInboundDetalis p : pyInbound.getPyInboundDetalisList()) {
            if (p == null) {
                continue; // 如果明细为 null，跳过
            }

            WhInventory whInventory = new WhInventory();
            whInventory.setLocationCode(p.getLocationCode());
            whInventory.setProductCode(p.getProductCode());

            // 查询库存信息
            WhInventory whInventory1 = pyInboundDetalisService.SelectWhInventoryInventoryUpperLimit(whInventory);
            System.out.println("whInventory1:" + whInventory1);

            // 检查 whInventory1 是否为 null
            if (whInventory1 == null) {
                System.out.println("未找到库存信息，跳过该明细。");
                continue; // 如果为 null，跳过当前循环，继续处理下一个入库明细
            }

            // 计算总库存，确保在 whInventory1 不为 null 的情况下访问其属性
            Integer total = whInventory1.getCurrentInventory() + p.getQuantityThisTime();
            System.out.println("whInventory1.getInventoryUpperLimit():" + whInventory1.getInventoryUpperLimit());
            System.out.println("总库存:" + total);

            // 检查库存上限
            if (whInventory1.getInventoryUpperLimit() < total) {
                return AjaxResult.warn("库存不能高于货品库存上限，不允许入库！", null);
            }
        }

        // 执行入库操作
        int i = pyInboundService.insertPyInbound(pyInbound);
        return toAjax(i);
    }


    @RequiresPermissions("inbound:inbound:check")
    @PostMapping("/updateStatus")
    public AjaxResult updateStatus(@RequestBody PyInbound pyInbound) {
        System.out.println("修改状态:" + pyInbound);
        pyInbound.setSureMan(SecurityUtils.getUserId());
        pyInbound.setSureDate(String.valueOf(new Date()));
        int i = pyInboundService.updateStatus(pyInbound);
        System.out.println("修改成功:" + i);
        return toAjax(i);
    }

    @GetMapping("/inPyInboundLS")
    public TableDataInfo inPyInboundLS(PyInbound pyInbound) {
//        System.out.println("PyInbound111:" + pyInbound);
        startPage();
        List<PyInbound> list = pyInboundService.inPyInboundLS(pyInbound);
        return getDataTable(list);
    }

    @GetMapping("/inTotal")
    public PyInbound inTotal() {

        return pyInboundService.inTotal();
    }
}
